package org.company.ci.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.company.ci.domain.Proveedor;
import org.company.ci.services.ProveedorService;
import org.company.ci.services.ServiceFinder;

/**
 * Servlet encargado de cargar la lista de proveedores.
 * Servlet implementation class CargarProveedoresServlet
 */
public class CargarProveedoresServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ServletConfig config;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CargarProveedoresServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		this.config = config;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// se llama al servicio de proveedores.
		ProveedorService proveedorService = (ProveedorService) ServiceFinder.getBean(
				config.getServletContext(),"proveedorService");
		
		ArrayList<Proveedor> proveedores = new ArrayList<Proveedor>();
		// se consulta la lista de proveedores.
		try {
			proveedores = proveedorService.getListProveedores();
		} catch (Exception e) {
			e.printStackTrace();
		}
		PrintWriter pw = response.getWriter();
		//por cada proveedor se crea el option que sera incrustado mediante ajax.
		pw.println("<option value='0' selected='selected'>Seleccione un Proveedor</option>");
		for (Proveedor prov : proveedores) { 
			String option = "<option value='"+prov.getIdProveedor()+"'>"+prov.getNombre()+"</option>";
			
			pw.println(option);
		
	   }
	}

}
